home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1522 < prev    next >
Encoding:
Text File  |  1996-08-05  |  55.3 KB  |  1,854 lines

  1. Newsgroups: comp.lang.c,comp.answers,news.answers
  2. Path: news.sprintlink.net!eskimo!scs
  3. From: scs@eskimo.com (Steve Summit)
  4. Subject: comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ)
  5. X-Nntp-Posting-Host: eskimo.com
  6. Message-ID: <1996Jan15.0300.scs.0001@eskimo.com>
  7. Followup-To: poster
  8. Originator: scs@eskimo.com
  9. Sender: news@eskimo.com (News User Id)
  10. Supersedes: <1996Jan01.0305.scs.0003@eskimo.com>
  11. Reply-To: scs@eskimo.com
  12. X-Pgp-Signature: Version: 2.6
  13.     iQCSAwUBME32e96sm4I1rmP1AQHSFgPlHNjSqomMN2TbUiz+dkDx1+tZyrEJSVh4
  14.     OJxD04jgNZrDrfwZFFRICFoC7S9tVDD+Qa7xSXZcM8Cba3TZPy8BCC5knGYpH6Az
  15.     QuOgAIrzuXq67Z9Gxi3HpW4qUqql19AUyySp7v5aq4AK1Ee5CZlEX+KtfUkVblz+
  16.     RCrpFFc=
  17.     =lhtB
  18. X-Archive-Name: C-faq/abridged
  19. Organization: only when absolutely necessary
  20. X-Version: 3.1a
  21. Date: Mon, 15 Jan 1996 11:02:50 GMT
  22. X-Last-Modified: November 1, 1995
  23. Approved: news-answers-request@MIT.Edu
  24. Expires: Sat, 3 Feb 1996 00:00:00 GMT
  25. X-Url: http://www.eskimo.com/~scs/C-faq.top.html
  26.  
  27. Archive-name: C-faq/abridged
  28. Comp-lang-c-archive-name: C-FAQ-list.abridged
  29. URL: http://www.eskimo.com/~scs/C-faq.top.html
  30.  
  31. [Last modified November 1, 1995 by scs.]
  32.  
  33. This article is Copyright 1990-1995 by Steve Summit.  Content from the
  34. book _C Programming FAQs: Frequently Asked Questions_ is made available
  35. here by permission of the author and the publisher as a service to the
  36. community.  It is intended to complement the use of the published text
  37. and is protected by international copyright laws.  The content is made
  38. available here and may be accessed freely for personal use but may not
  39. be published or retransmitted without written permission.
  40.  
  41. This article contains minimal answers to the comp.lang.c frequently-
  42. asked questions list.  More detailed explanations and references can be
  43. found in the long version (see question 20.40 for availability, or ftp
  44. to rtfm.mit.edu, or send the mail message "help" to mail-server@rtfm.mit.edu),
  45. and in the web version at <http://www.eskimo.com/~scs/C-faq.top.html>,
  46. and in the book _C Programming FAQs: Frequently Asked Questions_
  47. (Addison-Wesley, ISBN 0-201-84519-9).
  48.  
  49. Section 1. Declarations and Initializations
  50.  
  51. 1.1:    How do you decide which integer type to use?
  52.  
  53. A:    If you might need large values, use long.  Otherwise, if space
  54.     is very important, use short.  Otherwise, use int.
  55.  
  56. 1.4:    What should the 64-bit type on new, 64-bit machines be?
  57.  
  58. A:    There are arguments in favor of long int and long long int,
  59.     among other options.
  60.  
  61. 1.7:    What's the best way to declare and define global variables?
  62.  
  63. A:    The best arrangement is to place each definition in some
  64.     relevant .c file, with an external declaration in a header file.
  65.  
  66. 1.11:    What does extern mean in a function declaration?
  67.  
  68. A:    Nothing, really.
  69.  
  70. 1.12:    What's the auto keyword good for?
  71.  
  72. A:    Nothing.
  73.  
  74. 1.14:    I can't seem to define a linked list node which contains a
  75.     pointer to itself.
  76.  
  77. A:    Structures in C can certainly contain pointers to themselves;
  78.     the discussion and example in section 6.5 of K&R make this
  79.     clear.  Problems arise if an attempt is made to define (and use)
  80.     a typedef in the midst of such a declaration; avoid this.
  81.  
  82. 1.21:    How do I declare an array of N pointers to functions returning
  83.     pointers to functions returning pointers to characters?
  84.  
  85. A:    char *(*(*a[N])())();
  86.     Using a chain of typedefs, or the cdecl program, makes these
  87.     declarations easier.
  88.  
  89. 1.22:    How can I declare a function that returns a pointer to a
  90.     function of its own type?
  91.  
  92. A:    You can't quite do it directly.  Use a cast, or wrap a struct
  93.     around the pointer and return that.
  94.  
  95. 1.25:    My compiler is complaining about an invalid redeclaration of a
  96.     function, but I only define it once and call it once.
  97.  
  98. A:    Non-int functions must be declared before they are called.
  99.  
  100. 1.30:    What can I safely assume about the initial values of variables
  101.     which are not explicitly initialized?
  102.  
  103. A:    Variables with "static" duration start out as 0, as if the
  104.     programmer had initialized them.  Variables with "automatic"
  105.     duration, and dynamically-allocated memory, start out containing
  106.     garbage (with the exception of calloc).
  107.  
  108. 1.31:    Why can't I initialize a local array with a string?
  109.  
  110. A:    Perhaps you have a pre-ANSI compiler.
  111.  
  112. 1.32:    What is the difference between char a[] = "string"; and
  113.     char *p = "string"; ?
  114.  
  115. A:    The first declares an initialized and modifiable array; the
  116.     second declares a pointer initialized to a non-modifiable
  117.     constant string.
  118.  
  119. 1.34:    How do I initialize a pointer to a function?
  120.  
  121. A:    Use something like "extern int func(); int (*fp)() = func;" .
  122.  
  123.  
  124. Section 2. Structures, Unions, and Enumerations
  125.  
  126. 2.1:    What's the difference between struct x1 { ... }; and
  127.     typedef struct { ... } x2; ?
  128.  
  129. A:    The first structure is named by a tag, the second by a typedef
  130.     name.
  131.  
  132. 2.2:    Why doesn't "struct x { ... }; x thestruct;" work?
  133.  
  134. A:    C is not C++.
  135.  
  136. 2.3:    Can a structure contain a pointer to itself?
  137.  
  138. A:    See question 1.14.
  139.  
  140. 2.4:    What's the best way of implementing opaque (abstract) data types
  141.     in C?
  142.  
  143. A:    One good way is to use structure pointers which point to
  144.     structure types which are not publicly defined.
  145.  
  146. 2.6:    I came across some code that declared a structure with the last
  147.     member an array of one element, and then did some tricky
  148.     allocation to make it act like the array had several elements.
  149.     Is this legal or portable?
  150.  
  151. A:    An official interpretation has deemed that it is not strictly
  152.     conforming with the C Standard.
  153.  
  154. 2.7:    I heard that structures could be assigned to variables and
  155.     passed to and from functions, but K&R1 says not.
  156.  
  157. A:    These operations are supported by all modern compilers.
  158.  
  159. 2.8:    Why can't you compare structures?
  160.  
  161. A:    There is no single, good way for a compiler to implement
  162.     structure comparison which is consistent with C's low-level
  163.     flavor.
  164.  
  165. 2.9:    How are structure passing and returning implemented?
  166.  
  167. A:    If you really need to know, see the unabridged list.
  168.  
  169. 2.10:    Can I pass constant values to functions which accept structure
  170.     arguments?
  171.  
  172. A:    No.  C has no way of generating anonymous structure values.
  173.  
  174. 2.11:    How can I read/write structures from/to data files?
  175.  
  176. A:    It is relatively straightforward to use fread and fwrite.
  177.  
  178. 2.12:    How can I turn off structure padding?
  179.  
  180. A:    There is no standard method.
  181.  
  182. 2.13:    Why does sizeof report a larger size than I expect for a
  183.     structure type?
  184.  
  185. A:    The alignment of arrays of structures must be preserved.
  186.  
  187. 2.14:    How can I determine the byte offset of a field within a
  188.     structure?
  189.  
  190. A:    ANSI C defines the offsetof() macro, which should be used if
  191.     available.
  192.  
  193. 2.15:    How can I access structure fields by name at run time?
  194.  
  195. A:    Build a table of names and offsets, using the offsetof() macro.
  196.  
  197. 2.18:    I have a program which works correctly, but dumps core after it
  198.     finishes.  Why?
  199.  
  200. A:    Check to see if a structure type declaration just before main()
  201.     is missing its trailing semicolon, causing main() to be declared
  202.     as returning a structure.  See also questions 10.9 and 16.4.
  203.  
  204. 2.20:    Can I initialize unions?
  205.  
  206. A:    ANSI Standard C allows an initializer for the first member.
  207.  
  208. 2.22:    What is the difference between an enumeration and a set of
  209.     preprocessor #defines?
  210.  
  211. A:    At the present time, there is little difference.  The C Standard
  212.     states that enumerations are compatible with integral types.
  213.  
  214. 2.24:    Is there an easy way to print enumeration values symbolically?
  215.  
  216. A:    No.
  217.  
  218.  
  219. Section 3. Expressions
  220.  
  221. 3.1:    Why doesn't the code "a[i] = i++;" work?
  222.  
  223. A:    The variable i is both referenced and modified in the same
  224.     expression.
  225.  
  226. 3.2:    Under my compiler, the code "int i = 7;
  227.     printf("%d\n", i++ * i++);" prints 49.  Regardless of the order
  228.     of evaluation, shouldn't it print 56?
  229.  
  230. A:    The operations implied by the postincrement and postdecrement
  231.     operators ++ and -- are performed at some time after the
  232.     operand's former values are yielded and before the end of the
  233.     expression, but not necessarily immediately after, or before
  234.     other parts of the expression are evaluated.
  235.  
  236. 3.3:    How could the code "int i = 3; i = i++;" ever give 7?
  237.  
  238. A:    Undefined behavior means *anything* can happen.
  239.  
  240. 3.4:    Don't precedence and parentheses dictate order of evaluation?
  241.  
  242. A:    Operator precedence and explicit parentheses impose only a
  243.     partial ordering on the evaluation of an expression, which does
  244.     not generally include the order of side effects.
  245.  
  246. 3.5:    But what about the && and || operators?
  247.  
  248. A:    There is a special exception for those operators: left-to-right
  249.     evaluation is guaranteed.
  250.  
  251. 3.8:    What's a "sequence point"?
  252.  
  253. A:    The point (at the end of a full expression, or at the ||, &&,
  254.     ?:, or comma operators, or just before a function call) at which
  255.     all side effects are guaranteed to be complete.
  256.  
  257. 3.9:    So given a[i] = i++; we don't know which cell of a[] gets
  258.     written to, but i does get incremented by one.
  259.  
  260. A:    *No.*  Once an expression or program becomes undefined, *all*
  261.     aspects of it become undefined.
  262.  
  263. 3.12:    If I'm not using the value of the expression, should I use i++
  264.     or ++i to increment a variable?
  265.  
  266. A:    Since the two forms differ only in the value yielded, they are
  267.     entirely equivalent when only their side effect is needed.
  268.  
  269. 3.14:    Why doesn't the code "int a = 1000, b = 1000;
  270.     long int c = a * b;" work?
  271.  
  272. A:    You must manually cast one of the operands to (long).
  273.  
  274. 3.16:    Can I use ?: on the left-hand side of an assignment expression?
  275.  
  276. A:    No.
  277.  
  278.  
  279. Section 4. Pointers
  280.  
  281. 4.2:    What's wrong with "char *p; *p = malloc(10);"?
  282.  
  283. A:    The pointer you declared is p, not *p.
  284.  
  285. 4.3:    Does *p++ increment p, or what it points to?
  286.  
  287. A:    *p++ increments p.  To increment the value pointed to by p, use
  288.     (*p)++ .
  289.  
  290. 4.5:    I want to use a char * pointer to step over some ints.  Why
  291.     doesn't "((int *)p)++;" work?
  292.  
  293. A:    In C, a cast operator is a conversion operator, and by
  294.     definition it yields an rvalue, which cannot be assigned to, or
  295.     incremented with ++.
  296.  
  297. 4.8:    I have a function which accepts, and is supposed to initialize,
  298.     a pointer, but the pointer in the caller remains unchanged.
  299.  
  300. A:    The called function probably altered only the passed copy of the
  301.     pointer.
  302.  
  303. 4.9:    Can I use a void ** pointer to pass a generic pointer to a
  304.     function by reference?
  305.  
  306. A:    Not portably.
  307.  
  308. 4.10:    I have a function which accepts a pointer to an int.  How can I
  309.     pass a constant like 5 to it?
  310.  
  311. A:    You will have to declare a temporary variable.
  312.  
  313. 4.11:    Does C even have "pass by reference"?
  314.  
  315. A:    Not really, though it can be simulated.
  316.  
  317. 4.12:    I've seen different methods used for calling functions via
  318.     pointers.
  319.  
  320. A:    The extra parentheses and explicit * are now officially
  321.     optional, although some older implementations require them.
  322.  
  323.  
  324. Section 5. Null Pointers
  325.  
  326. 5.1:    What is this infamous null pointer, anyway?
  327.  
  328. A:    For each pointer type, there is a special value -- the "null
  329.     pointer" -- which is distinguishable from all other pointer
  330.     values and which is not the address of any object or function.
  331.  
  332. 5.2:    How do I get a null pointer in my programs?
  333.  
  334. A:    A constant 0 in a pointer context is converted into a null
  335.     pointer at compile time.  A "pointer context" is an
  336.     initialization, assignment, or comparison with one side a
  337.     variable or expression of pointer type, and (in ANSI standard C)
  338.     a function argument which has a prototype in scope declaring a
  339.     certain parameter as being of pointer type.  In other contexts
  340.     (function arguments without prototypes, or in the variable part
  341.     of variadic function calls) a constant 0 with an appropriate
  342.     explicit cast is required.
  343.  
  344. 5.3:    Is the abbreviated pointer comparison "if(p)" to test for non-
  345.     null pointers valid?
  346.  
  347. A:    Yes.  The construction "if(p)" works, regardless of the internal
  348.     representation of null pointers, because the compiler
  349.     essentially rewrites it as "if(p != 0)" and goes on to convert 0
  350.     into the correct null pointer.
  351.  
  352. 5.4:    What is NULL and how is it #defined?
  353.  
  354. A:    NULL is simply a preprocessor macro, #defined as 0 (or
  355.     ((void *)0)), which is used (as a stylistic convention, in
  356.     preference to unadorned 0's) to generate null pointers.
  357.  
  358. 5.5:    How should NULL be defined on a machine which uses a nonzero bit
  359.     pattern as the internal representation of a null pointer?
  360.  
  361. A:    The same as on any other machine: as 0 (or ((void *)0)).  (The
  362.     compiler makes the translation, upon seeing a 0, not the
  363.     preprocessor.)
  364.  
  365. 5.6:    If NULL were defined as "((char *)0)," wouldn't that make
  366.     function calls which pass an uncast NULL work?
  367.  
  368. A:    Not in general.  The problem is that there are machines which
  369.     use different internal representations for pointers to different
  370.     types of data.  A cast is still required to tell the compiler
  371.     which kind of null pointer is required, since it may be
  372.     different from (char *)0.
  373.  
  374. 5.9:    If NULL and 0 are equivalent as null pointer constants, which
  375.     should I use?
  376.  
  377. A:    Either; the distinction is entirely stylistic.
  378.  
  379. 5.10:    But wouldn't it be better to use NULL, in case the value of NULL
  380.     changes?
  381.  
  382. A:    No.  NULL is, and will always be, 0.
  383.  
  384. 5.12:    I use the preprocessor macro "#define Nullptr(type) (type *)0"
  385.     to help me build null pointers of the correct type.
  386.  
  387. A:    This trick, though valid, does not buy much.
  388.  
  389. 5.13:    This is strange.  NULL is guaranteed to be 0, but the null
  390.     pointer is not?
  391.  
  392. A:    A "null pointer" is a language concept whose particular internal
  393.     value does not matter.  A null pointer is requested in source
  394.     code with the character "0".  "NULL" is a preprocessor macro,
  395.     which is always #defined as 0 (or ((void *)0)).
  396.  
  397. 5.14:    Why is there so much confusion surrounding null pointers?
  398.  
  399. A:    The fact that null pointers are represented both in source code,
  400.     and internally to most machines, as zero invites unwarranted
  401.     assumptions.  The use of a preprocessor macro (NULL) may seem to
  402.     suggest that the value could change some day, or on some weird
  403.     machine.
  404.  
  405. 5.15:    I'm confused.  I just can't understand all this null pointer
  406.     stuff.
  407.  
  408. A:    A simple rule is, "Always use `0' or `NULL' for null pointers,
  409.     and always cast them when they are used as arguments in function
  410.     calls."
  411.  
  412. 5.16:    Given all the confusion surrounding null pointers, wouldn't it
  413.     be easier simply to require them to be represented internally by
  414.     zeroes?
  415.  
  416. A:    Such a requirement would accomplish little.
  417.  
  418. 5.17:    Seriously, have any actual machines really used nonzero null
  419.     pointers?
  420.  
  421. A:    Machines manufactured by Prime, Honeywell-Bull, and CDC, as well
  422.     as Symbolics Lisp Machines, have done so.
  423.  
  424. 5.20:    What does a run-time "null pointer assignment" error mean?
  425.  
  426. A:    It means that you've written, via a null pointer, to location 0.
  427.     (See also question 16.8.)
  428.  
  429.  
  430. Section 6. Arrays and Pointers
  431.  
  432. 6.1:    I had the definition char a[6] in one source file, and in
  433.     another I declared extern char *a.  Why didn't it work?
  434.  
  435. A:    The declaration extern char *a simply does not match the actual
  436.     definition.  Use extern char a[].
  437.  
  438. 6.2:    But I heard that char a[] was identical to char *a.
  439.  
  440. A:    Not at all.  Arrays are not pointers.  A reference like *x*[3]
  441.     generates different code depending on whether *x* is an array or
  442.     a pointer.
  443.  
  444. 6.3:    So what is meant by the "equivalence of pointers and arrays" in
  445.     C?
  446.  
  447. A:    An lvalue of type array-of-T which appears in an expression
  448.     decays into a pointer to its first element; the type of the
  449.     resultant pointer is pointer-to-T.  So for an array a and
  450.     pointer p, you can say "p = a;" and then p[3] and a[3] will
  451.     access the same element.
  452.  
  453. 6.4:    Why are array and pointer declarations interchangeable as
  454.     function formal parameters?
  455.  
  456. A:    It's supposed to be a convenience.
  457.  
  458. 6.7:    How can an array be an lvalue, if you can't assign to it?
  459.  
  460. A:    An array is not a "modifiable lvalue."
  461.  
  462. 6.8:    What is the real difference between arrays and pointers?
  463.  
  464. A:    Arrays automatically allocate space which is fixed in size and
  465.     location; pointers are dynamic.
  466.  
  467. 6.9:    Someone explained to me that arrays were really just constant
  468.     pointers.
  469.  
  470. A:    An array name is "constant" in that it cannot be assigned to,
  471.     but an array is *not* a pointer.
  472.  
  473. 6.11:    I came across some "joke" code containing the "expression"
  474.     5["abcdef"] .  How can this be legal C?
  475.  
  476. A:    Yes, array subscripting is commutative in C.  The array
  477.     subscripting operation a[e] is defined as being identical to
  478.     *((a)+(e)).
  479.  
  480. 6.12:    What's the difference between array and &array?
  481.  
  482. A:    The type.
  483.  
  484. 6.13:    How do I declare a pointer to an array?
  485.  
  486. A:    Usually, you don't want to.  Consider using a pointer to one of
  487.     the array's elements instead.
  488.  
  489. 6.14:    How can I set an array's size at compile time?
  490.  
  491. A:    It's straightforward to use malloc() and a pointer.
  492.  
  493. 6.15:    How can I declare local arrays of a size matching a passed-in
  494.     array?
  495.  
  496. A:    You can't; array dimensions must be compile-time constants.
  497.  
  498. 6.16:    How can I dynamically allocate a multidimensional array?
  499.  
  500. A:    It is usually best to allocate an array of pointers, and then
  501.     initialize each pointer to a dynamically-allocated "row."  See
  502.     the full list for code samples.
  503.  
  504. 6.17:    Can I simulate a non-0-based array with a pointer?
  505.  
  506. A:    Not if the pointer points outside of the block of memory it is
  507.     intended to access.
  508.  
  509. 6.18:    My compiler complained when I passed a two-dimensional array to
  510.     a function expecting a pointer to a pointer.
  511.  
  512. A:    The rule by which arrays decay into pointers is not applied
  513.     recursively.  An array of arrays (i.e. a two-dimensional array
  514.     in C) decays into a pointer to an array, not a pointer to a
  515.     pointer.
  516.  
  517. 6.19:    How do I write functions which accept two-dimensional arrays
  518.     when the "width" is not known at compile time?
  519.  
  520. A:    It's not particularly easy.
  521.  
  522. 6.20:    How can I use statically- and dynamically-allocated
  523.     multidimensional arrays interchangeably when passing them to
  524.     functions?
  525.  
  526. A:    There is no single perfect method, but see the full list for
  527.     some ideas.
  528.  
  529. 6.21:    Why doesn't sizeof properly report the size of an array which is
  530.     a parameter to a function?
  531.  
  532. A:    The sizeof operator reports the size of the pointer parameter
  533.     which the function actually receives.
  534.  
  535.  
  536. Section 7. Memory Allocation
  537.  
  538. 7.1:    Why doesn't the code "char *answer; gets(answer);" work?
  539.  
  540. A:    The pointer variable answer() has not been set to point to any
  541.     valid storage.  The simplest way to correct this fragment is to
  542.     use a local array, instead of a pointer.
  543.  
  544. 7.2:    I can't get strcat() to work.  I tried "char *s3 =
  545.     strcat(s1, s2);" but I got strange results.
  546.  
  547. A:    Again, the main problem here is that space for the concatenated
  548.     result is not properly allocated.
  549.  
  550. 7.3:    But the man page for strcat() says that it takes two char *'s as
  551.     arguments.  How am I supposed to know to allocate things?
  552.  
  553. A:    In general, when using pointers you *always* have to consider
  554.     memory allocation, if only to make sure that the compiler is
  555.     doing it for you.
  556.  
  557. 7.5:    I have a function that is supposed to return a string, but when
  558.     it returns to its caller, the returned string is garbage.
  559.  
  560. A:    Make sure that the pointed-to memory is properly (i.e. not
  561.     locally) allocated.
  562.  
  563. 7.6:    Why am I getting "warning: assignment of pointer from integer
  564.     lacks a cast" for calls to malloc()?
  565.  
  566. A:    Have you #included <stdlib.h>?
  567.  
  568. 7.7:    Why does some code carefully cast the values returned by malloc
  569.     to the pointer type being allocated?
  570.  
  571. A:    Before ANSI/ISO C, these casts were required to silence certain
  572.     warnings.
  573.  
  574. 7.8:    Why does so much code leave out the multiplication by
  575.     sizeof(char) when allocating strings?
  576.  
  577. A:    Because sizeof(char) is, by definition, exactly 1.
  578.  
  579. 7.14:    I've heard that some operating systems don't actually allocate
  580.     malloc()'ed memory until the program tries to use it.  Is this
  581.     legal?
  582.  
  583. A:    It's hard to say.
  584.  
  585. 7.16:    I'm allocating a large array for some numeric work, but malloc()
  586.     is acting strangely.
  587.  
  588. A:    Make sure the number you're trying to pass to malloc() isn't
  589.     bigger than a size_t can hold.
  590.  
  591. 7.17:    I've got 8 meg of memory in my PC.  Why can I only seem to
  592.     malloc() 640K or so?
  593.  
  594. A:    Under the segmented architecture of PC compatibles, it can be
  595.     difficult to use more than 640K with any degree of transparency.
  596.     See also question 19.23.
  597.  
  598. 7.19:    My program is crashing, apparently somewhere down inside malloc.
  599.  
  600. A:    Make sure you aren't using more memory than you malloc'ed,
  601.     especially for strings (which need strlen(str) + 1 bytes).
  602.  
  603. 7.20:    You can't use dynamically-allocated memory after you free it,
  604.     can you?
  605.  
  606. A:    No.  Some early documentation implied otherwise, but the claim
  607.     is no longer valid.
  608.  
  609. 7.21:    Why isn't a pointer null after calling free()?
  610.  
  611. A:    C's pass-by-value semantics mean that called functions can never
  612.     permanently change the values of their arguments.
  613.  
  614. 7.22:    When I call malloc() to allocate memory for a local pointer, do
  615.     I have to explicitly free() it?
  616.  
  617. A:    Yes.
  618.  
  619. 7.23:    When I free a dynamically-allocated structure containing
  620.     pointers, do I have to free each subsidiary pointer first?
  621.  
  622. A:    Yes.
  623.  
  624. 7.24:    Must I free allocated memory before the program exits?
  625.  
  626. A:    You shouldn't have to.
  627.  
  628. 7.25:    Why doesn't my program's memory usage go down when I free
  629.     memory?
  630.  
  631. A:    Most implementations of malloc/free do not return freed memory
  632.     to the operating system.
  633.  
  634. 7.26:    How does free() know how many bytes to free?
  635.  
  636. A:    The malloc/free implementation remembers the size of each block
  637.     allocated and returned.
  638.  
  639. 7.27:    So can I query the malloc package to find out how big an
  640.     allocated block is?
  641.  
  642. A:    Not portably.
  643.  
  644. 7.30:    Is it legal to pass a null pointer as the first argument to
  645.     realloc()?
  646.  
  647. A:    ANSI C sanctions this usage, although several earlier
  648.     implementations do not support it.
  649.  
  650. 7.31:    What's the difference between calloc() and malloc()?
  651.  
  652. A:    calloc() takes two arguments, and initializes the allocated
  653.     memory to all-bits-0.
  654.  
  655. 7.32:    What is alloca() and why is its use discouraged?
  656.  
  657. A:    alloca() allocates memory which is automatically freed when the
  658.     function which called alloca() returns.  alloca() cannot be
  659.     written portably, is difficult to implement on machines without
  660.     a stack, and fails under certain conditions if implemented
  661.     simply.
  662.  
  663.  
  664. Section 8. Characters and Strings
  665.  
  666. 8.1:    Why doesn't "strcat(string, '!');" work?
  667.  
  668. A:    strcat() concatenates *strings*, not characters.
  669.  
  670. 8.2:    Why won't the test if(string == "value") correctly compare
  671.     string against the value?
  672.  
  673. A:    It's comparing the pointers.  To compare two strings, use
  674.     strcmp().
  675.  
  676. 8.3:    Why can't I assign strings to character arrays?
  677.  
  678. A:    Strings are arrays, and you can't assign arrays directly.  Use
  679.     strcpy() instead.
  680.  
  681. 8.6:    How can I get the numeric (character set) value corresponding to
  682.     a character?
  683.  
  684. A:    In C, if you have the character, you have its value.
  685.  
  686. 8.9:    Why is sizeof('a') not 1?
  687.  
  688. A:    Character constants in C are of type int.
  689.  
  690.  
  691. Section 9. Boolean Expressions
  692.  
  693. 9.1:    What is the right type to use for Boolean values in C?
  694.  
  695. A:    There's no one right answer; see the full list for some
  696.     discussion.
  697.  
  698. 9.2:    What if a built-in logical or relational operator "returns"
  699.     something other than 1?
  700.  
  701. A:    When a Boolean value is generated by a built-in operator, it is
  702.     guaranteed to be 1 or 0.  (This is *not* true for some library
  703.     routines such as isalpha.)
  704.  
  705. 9.3:    Is if(p), where p is a pointer, valid?
  706.  
  707. A:    Yes.  See question 5.3.
  708.  
  709.  
  710. Section 10. C Preprocessor
  711.  
  712. 10.2:    I've got some cute preprocessor macros that let me write C code
  713.     that looks more like Pascal.  What do y'all think?
  714.  
  715. A:    Bleah.
  716.  
  717. 10.3:    How can I write a generic macro to swap two values?
  718.  
  719. A:    There is no good answer to this question.  The best all-around
  720.     solution is probably to forget about using a macro.
  721.  
  722. 10.4:    What's the best way to write a multi-statement macro?
  723.  
  724. A:    #define Func() do {stmt1; stmt2; ... } while(0)    /* (no trailing ;) */
  725.  
  726. 10.6:    What are .h files and what should I put in them?
  727.  
  728. A:    Header files (also called ".h files") should generally contain
  729.     common declarations and macro, structure, and typedef
  730.     definitions, but not variable or function definitions.
  731.  
  732. 10.7:    Is it acceptable for one header file to #include another?
  733.  
  734. A:    It's a question of style, and thus receives considerable debate.
  735.  
  736. 10.8:    Where are header ("#include") files searched for?
  737.  
  738. A:    The exact behavior is implementation-defined; see the full list
  739.     for some discussion.
  740.  
  741. 10.9:    I'm getting strange syntax errors on the very first declaration
  742.     in a file, but it looks fine.
  743.  
  744. A:    Perhaps there's a missing semicolon at the end of the last
  745.     declaration in the last header file you're #including.
  746.  
  747. 10.11:    Where can I get a copy of a missing header file?
  748.  
  749. A:    Contact your vendor, or see question 18.16 or the full list.
  750.  
  751. 10.12:    How can I construct preprocessor #if expressions which compare
  752.     strings?
  753.  
  754. A:    You can't do it directly; try #defining several manifest
  755.     constants and implementing conditionals on those.
  756.  
  757. 10.13:    Does the sizeof operator work in preprocessor #if directives?
  758.  
  759. A:    No.
  760.  
  761. 10.14:    Can I use an #ifdef in a #define line, to define something two
  762.     different ways?
  763.  
  764. A:    No.
  765.  
  766. 10.15:    Is there anything like an #ifdef for typedefs?
  767.  
  768. A:    Unfortunately, no.
  769.  
  770. 10.16:    How can I use a preprocessor #if expression to detect
  771.     endianness?
  772.  
  773. A:    You probably can't.
  774.  
  775. 10.18:    How can I preprocess some code to remove selected conditional
  776.     compilations, without preprocessing everything?
  777.  
  778. A:    Look for a program called unifdef, rmifdef, or scpp.
  779.  
  780. 10.19:    How can I list all of the pre#defined identifiers?
  781.  
  782. A:    If the compiler documentation is unhelpful, try extracting
  783.     printable strings from the compiler or preprocessor executable.
  784.  
  785. 10.20:    I have some old code that tries to construct identifiers with a
  786.     macro like "#define Paste(a, b) a/**/b", but it doesn't work any
  787.     more.
  788.  
  789. A:    Try the ANSI token-pasting operator ##.
  790.  
  791. 10.22:    What does the message "warning: macro replacement within a
  792.     string literal" mean?
  793.  
  794. A:    See question 11.18.
  795.  
  796. 10.23:    How can I use a macro argument inside a string literal in the
  797.     macro expansion?
  798.  
  799. A:    See question 11.18.
  800.  
  801. 10.25:    I've got this tricky preprocessing I want to do and I can't
  802.     figure out a way to do it.
  803.  
  804. A:    Consider writing your own little special-purpose preprocessing
  805.     tool, instead.
  806.  
  807. 10.26:    How can I write a macro which takes a variable number of
  808.     arguments?
  809.  
  810. A:    Here is one popular trick.  Note that the parentheses around
  811.     printf's argument list are in the macro call, not the
  812.     definition.
  813.  
  814.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  815.  
  816.         if(n != 0) DEBUG(("n is %d\n", n));
  817.  
  818.  
  819. Section 11. ANSI/ISO Standard C
  820.  
  821. 11.1:    What is the "ANSI C Standard?"
  822.  
  823. A:    In 1983, the American National Standards Institute (ANSI)
  824.     commissioned a committee to standardize the C language.  Their
  825.     work was ratified as ANS X3.159-1989, and has since been adopted
  826.     as ISO/IEC 9899:1990.
  827.  
  828. 11.2:    How can I get a copy of the Standard?
  829.  
  830. A:    Copies are available from ANSI in New York, or from Global
  831.     Engineering Documents in Englewood, CO, or from any national
  832.     Standards body, or from ISO in Geneva, or republished within one
  833.     or more books.  See the unabridged list for details.
  834.  
  835. 11.3:    My ANSI compiler is complaining about prototype mismatches for
  836.     parameters declared float.
  837.  
  838. A:    You have mixed the new-style prototype declaration
  839.     "extern int func(float);" with the old-style definition
  840.     "int func(x) float x;".  "Narrow" types are treated differently
  841.     according to which syntax is used.  This problem can be fixed by
  842.     avoiding narrow types, or by using either new-style (prototype)
  843.     or old-style syntax consistently.
  844.  
  845. 11.4:    Can you mix old-style and new-style function syntax?
  846.  
  847. A:    Doing so is currently perfectly legal.
  848.  
  849. 11.5:    Why does the declaration "extern f(struct x *p);" give me a
  850.     warning message?
  851.  
  852. A:    A structure declared (or even mentioned) for the first time
  853.     within a prototype cannot be compatible with other structures
  854.     declared in the same source file.
  855.  
  856. 11.8:    Why can't I use const values in initializers and array
  857.     dimensions?
  858.  
  859. A:    The value of a const-qualified object is *not* a constant
  860.     expression in the full sense of the term.
  861.  
  862. 11.9:    What's the difference between "const char *p" and
  863.     "char * const p"?
  864.  
  865. A:    The former declares a pointer to a constant character; the
  866.     latter declares a constant pointer to a character.
  867.  
  868. 11.10:    Why can't I pass a char ** to a function which expects a
  869.     const char **?
  870.  
  871. A:    The rule which permits slight mismatches in qualified pointer
  872.     assignments is not applied recursively.
  873.  
  874. 11.12:    Can I declare main() as void, to shut off these annoying "main
  875.     returns no value" messages?
  876.  
  877. A:    No.
  878.  
  879. 11.13:    But what about main()'s third argument, envp?
  880.  
  881. A:    It's a non-standard (though common) extension.
  882.  
  883. 11.14:    I believe that declaring void main() can't fail, since I'm
  884.     calling exit() instead of returning.
  885.  
  886. A:    It doesn't matter whether main() returns or not, the problem is
  887.     that its caller may not even be able to *call* it correctly.
  888.  
  889. 11.15:    The book I've been using always uses void main().
  890.  
  891. A:    It's wrong.
  892.  
  893. 11.16:    Is exit(status) truly equivalent to returning the same status
  894.     from main()?
  895.  
  896. A:    Yes and no.  (See the full list for details.)
  897.  
  898. 11.17:    How do I get the ANSI "stringizing" preprocessing operator `#'
  899.     to stringize the macro's value instead of its name?
  900.  
  901. A:    You can use a two-step #definition to force a macro to be
  902.     expanded as well as stringized.
  903.  
  904. 11.18:    What does the message "warning: macro replacement within a
  905.     string literal" mean?
  906.  
  907. A:    Some pre-ANSI compilers/preprocessors expanded macro parameters
  908.     even inside string literals and character constants.
  909.  
  910. 11.19:    I'm getting strange syntax errors inside lines I've #ifdeffed
  911.     out.
  912.  
  913. A:    Under ANSI C, #ifdeffed-out text must still consist of "valid
  914.     preprocessing tokens."  This means that there must be no
  915.     newlines inside quotes, and no unterminated comments or quotes
  916.     (i.e. no single apostrophes).
  917.  
  918. 11.20:    What are #pragmas ?
  919.  
  920. A:    The #pragma directive provides a single, well-defined "escape
  921.     hatch" which can be used for extensions.
  922.  
  923. 11.21:    What does "#pragma once" mean?
  924.  
  925. A:    It is an extension implemented by some preprocessors to help
  926.     make header files idempotent.
  927.  
  928. 11.22:    Is char a[3] = "abc"; legal?
  929.  
  930. A:    Yes, in ANSI C.
  931.  
  932. 11.24:    Why can't I perform arithmetic on a void * pointer?
  933.  
  934. A:    The compiler doesn't know the size of the pointed-to objects.
  935.  
  936. 11.25:    What's the difference between memcpy() and memmove()?
  937.  
  938. A:    memmove() offers guaranteed behavior if the source and
  939.     destination arguments overlap.
  940.  
  941. 11.26:    What should malloc(0) do?
  942.  
  943. A:    The behavior is implementation-defined.
  944.  
  945. 11.27:    Why does the ANSI Standard not guarantee more than six case-
  946.     insensitive characters of external identifier significance?
  947.  
  948. A:    The problem is older linkers which cannot be forced (by mere
  949.     words in a Standard) to upgrade.
  950.  
  951. 11.29:    My compiler is rejecting the simplest possible test programs,
  952.     with all kinds of syntax errors.
  953.  
  954. A:    Perhaps it is a pre-ANSI compiler.
  955.  
  956. 11.30:    Why are some ANSI/ISO Standard library routines showing up as
  957.     undefined, even though I've got an ANSI compiler?
  958.  
  959. A:    Perhaps you don't have ANSI-compatible headers and libraries.
  960.  
  961. 11.31:    Does anyone have a tool for converting old-style C programs to
  962.     ANSI C, or for automatically generating prototypes?
  963.  
  964. A:    See the full list for details.
  965.  
  966. 11.32:    Why won't frobozz-cc, which claims to be ANSI compliant, accept
  967.     this code?
  968.  
  969. A:    Are you sure that the code being rejected doesn't rely on some
  970.     non-Standard extension?
  971.  
  972. 11.33:    What's the difference between implementation-defined,
  973.     unspecified, and undefined behavior?
  974.  
  975. A:    If you're writing portable code, ignore the distinctions.
  976.     Otherwise, see the full list.
  977.  
  978. 11.34:    I'm appalled that the ANSI Standard leaves so many issues
  979.     undefined.
  980.  
  981. A:    In most of these cases, the Standard is simply codifying
  982.     existing practice.
  983.  
  984. 11.35:    I just tried some allegedly-undefined code on an ANSI-conforming
  985.     compiler, and got the results I expected.
  986.  
  987. A:    A compiler may do anything it likes when faced with undefined
  988.     behavior, including doing what you expect.
  989.  
  990.  
  991. Section 12. Stdio
  992.  
  993. 12.1:    What's wrong with the code "char c; while((c = getchar()) !=
  994.     EOF) ..."?
  995.  
  996. A:    The variable to hold getchar()'s return value must be an int.
  997.  
  998. 12.2:    Why won't the code "while(!feof(infp)) {
  999.     fgets(buf, MAXLINE, infp); fputs(buf, outfp); }" work?
  1000.  
  1001. A:    EOF is only indicated *after* an input routine has reached end-
  1002.     of-file.
  1003.  
  1004. 12.4:    My program's prompts and intermediate output don't always show
  1005.     up on the screen.
  1006.  
  1007. A:    It's best to use an explicit fflush(stdout) whenever output
  1008.     should definitely be visible.
  1009.  
  1010. 12.5:    How can I read one character at a time, without waiting for the
  1011.     RETURN key?
  1012.  
  1013. A:    See question 19.1.
  1014.  
  1015. 12.6:    How can I print a '%' character with printf?
  1016.  
  1017. A:    %% .
  1018.  
  1019. 12.9:    How can printf() use %f for type double, if scanf() requires
  1020.     %lf?
  1021.  
  1022. A:    C's "default argument promotions" mean that values of type float
  1023.     are promoted to double.
  1024.  
  1025. 12.10:    How can I implement a variable field width with printf?
  1026.  
  1027. A:    Use printf("%*d", width, n).
  1028.  
  1029. 12.11:    How can I print numbers with commas separating the thousands?
  1030.  
  1031. A:    There is no standard routine (but see <locale.h>).
  1032.  
  1033. 12.12:    Why doesn't the call scanf("%d", i) work?
  1034.  
  1035. A:    The arguments you pass to scanf() must always be pointers.
  1036.  
  1037. 12.13:    Why doesn't the code "double d; scanf("%f", &d);" work?
  1038.  
  1039. A:    Unlike printf(), scanf() uses %lf for double, and %f for float.
  1040.  
  1041. 12.15:    How can I specify a variable width in a scanf() format string?
  1042.  
  1043. A:    You can't.
  1044.  
  1045. 12.17:    When I read numbers from the keyboard with scanf "%d\n", it
  1046.     seems to hang until I type one extra line of input.
  1047.  
  1048. A:    Try using "%d" instead of "%d\n".
  1049.  
  1050. 12.18:    I'm reading a number with scanf %d and then a string with
  1051.     gets(), but the compiler seems to be skipping the call to
  1052.     gets()!
  1053.  
  1054. A:    scanf() and gets() do not work well together.
  1055.  
  1056. 12.19:    I'm re-prompting the user if scanf() fails, but sometimes it
  1057.     seems to go into an infinite loop.
  1058.  
  1059. A:    scanf() tends to "jam" on bad input since it does not discard
  1060.     it.
  1061.  
  1062. 12.20:    Why does everyone say not to use scanf()?  What should I use
  1063.     instead?
  1064.  
  1065. A:    scanf() has a number of problems.  Usually, it's easier to read
  1066.     entire lines and then interpret them.
  1067.  
  1068. 12.21:    How can I tell how much destination buffer space I'll need for
  1069.     an arbitrary sprintf call?  How can I avoid overflowing the
  1070.     destination buffer with sprintf()?
  1071.  
  1072. A:    There are not (yet) any good answers to either of these
  1073.     excellent questions.
  1074.  
  1075. 12.23:    Why does everyone say not to use gets()?
  1076.  
  1077. A:    It cannot be prevented from overflowing the input buffer.
  1078.  
  1079. 12.24:    Why does errno contain ENOTTY after a call to printf()?
  1080.  
  1081. A:    Don't worry about it.  It is only meaningful for a program to
  1082.     inspect the contents of errno after an error has been reported.
  1083.  
  1084. 12.25:    What's the difference between fgetpos/fsetpos and ftell/fseek?
  1085.  
  1086. A:    fgetpos() and fsetpos() use a special typedef which may allow
  1087.     them to work with larger files than ftell() and fseek().
  1088.  
  1089. 12.26:    Will fflush(stdin) flush unread characters from the standard
  1090.     input stream?
  1091.  
  1092. A:    No.
  1093.  
  1094. 12.30:    I'm trying to update a file in place, by using fopen mode "r+",
  1095.     but it's not working.
  1096.  
  1097. A:    Be sure to call fseek between reading and writing.
  1098.  
  1099. 12.33:    How can I redirect stdin or stdout from within a program?
  1100.  
  1101. A:    Use freopen().
  1102.  
  1103. 12.34:    Once I've used freopen(), how can I get the original stream
  1104.     back?
  1105.  
  1106. A:    There isn't a good way.  Try avoiding freopen.
  1107.  
  1108. 12.38:    How can I read a binary data file properly?
  1109.  
  1110. A:    Be sure to specify "rb" mode when calling fopen().
  1111.  
  1112.  
  1113. Section 13. Library Functions
  1114.  
  1115. 13.1:    How can I convert numbers to strings?
  1116.  
  1117. A:    Just use sprintf().
  1118.  
  1119. 13.2:    Why does strncpy() not always write a '\0'?
  1120.  
  1121. A:    For mildly-interesting historical reasons.
  1122.  
  1123. 13.5:    Why do some versions of toupper() act strangely if given an
  1124.     upper-case letter?
  1125.  
  1126. A:    Older versions of toupper() and tolower() did not always work
  1127.     correctly in this regard.
  1128.  
  1129. 13.6:    How can I split up a string into whitespace-separated fields?
  1130.  
  1131. A:    Try strtok.
  1132.  
  1133. 13.7:    I need some code to do regular expression and wildcard matching.
  1134.  
  1135. A:    regexp libraries abound; see the full list for details.
  1136.  
  1137. 13.8:    I'm trying to sort an array of strings with qsort(), using
  1138.     strcmp() as the comparison function, but it's not working.
  1139.  
  1140. A:    You'll have to write a "helper" comparison function which takes
  1141.     two generic pointer arguments, converts them to char **, and
  1142.     dereferences them, yielding char *'s which can be usefully
  1143.     compared.
  1144.  
  1145. 13.9:    Now I'm trying to sort an array of structures, but the compiler
  1146.     is complaining that the function is of the wrong type for
  1147.     qsort().
  1148.  
  1149. A:    The comparison function must be declared as accepting "generic
  1150.     pointers" (const void *) which it then converts to structure
  1151.     pointers.
  1152.  
  1153. 13.10:    How can I sort a linked list?
  1154.  
  1155. A:    Algorithms like insertion sort and merge sort work well, or you
  1156.     can keep the list in order as you build it.
  1157.  
  1158. 13.11:    How can I sort more data than will fit in memory?
  1159.  
  1160. A:    You want an "external sort."
  1161.  
  1162. 13.12:    How can I get the time of day in a C program?
  1163.  
  1164. A:    Just use the time, ctime, and/or localtime functions.
  1165.  
  1166. 13.13:    How can I convert a struct tm or a string into a time_t?
  1167.  
  1168. A:    The ANSI mktime() routine converts a struct tm to a time_t.  No
  1169.     standard routine exists to parse strings.
  1170.  
  1171. 13.14:    How can I perform calendar manipulations?
  1172.  
  1173. A:    The ANSI/ISO Standard C mktime() and difftime() functions
  1174.     provide some support for both problems.
  1175.  
  1176. 13.15:    I need a random number generator.
  1177.  
  1178. A:    The Standard C library has one: rand().
  1179.  
  1180. 13.16:    How can I get random integers in a certain range?
  1181.  
  1182. A:    One method is something like
  1183.  
  1184.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  1185.  
  1186. 13.17:    Each time I run my program, I get the same sequence of numbers
  1187.     back from rand().
  1188.  
  1189. A:    You can call srand() to seed the pseudo-random number generator
  1190.     with a truly random initial value.
  1191.  
  1192. 13.18:    I need a random true/false value, so I'm just taking rand() % 2,
  1193.     but it's alternating 0, 1, 0, 1, 0...
  1194.  
  1195. A:    Try using the higher-order bits.
  1196.  
  1197. 13.20:    How can I generate random numbers with a normal or Gaussian
  1198.     distribution?
  1199.  
  1200. A:    See the longer versions of this list for ideas.
  1201.  
  1202. 13.24:    I'm trying to port this old program.  Why do I get "undefined
  1203.     external" errors for some library functions?
  1204.  
  1205. A:    Some semistandard functions have been renamed or replaced over
  1206.     the years; see the full list for details.
  1207.  
  1208. 13.25:    I get errors due to library functions being undefined even
  1209.     though I #include the right header files.
  1210.  
  1211. A:    You may have to explicitly ask for the correct libraries to be
  1212.     searched.
  1213.  
  1214. 13.26:    I'm still getting errors due to library functions being
  1215.     undefined, even though I'm requesting the right libraries.
  1216.  
  1217. A:    Library search order is significant; usually, you must search
  1218.     the libraries last.
  1219.  
  1220. 13.28:    What does it mean when the linker says that _end is undefined?
  1221.  
  1222. A:    You generally get that message only when other things are
  1223.     undefined, too.
  1224.  
  1225.  
  1226. Section 14. Floating Point
  1227.  
  1228. 14.1:    When I set a float variable to 3.1, why is printf() printing it
  1229.     as 3.0999999?
  1230.  
  1231. A:    Most computers use base 2 for floating-point numbers, and many
  1232.     fractions (including 0.1 decimal) are not exactly representable
  1233.     in base 2.
  1234.  
  1235. 14.2:    Why is sqrt(144.) giving me crazy numbers?
  1236.  
  1237. A:    Make sure that you have #included <math.h>, and correctly
  1238.     declared other functions returning double.
  1239.  
  1240. 14.3:    I keep getting "undefined: sin" compilation errors.
  1241.  
  1242. A:    Make sure you're actually linking with the math library.
  1243.  
  1244. 14.4:    My floating-point calculations are acting strangely and giving
  1245.     me different answers on different machines.
  1246.  
  1247. A:    First, see question 14.2 above.  If the problem isn't that
  1248.     simple, see the full list for a brief explanation, or any good
  1249.     programming book for a better one.
  1250.  
  1251. 14.5:    What's a good way to check for "close enough" floating-point
  1252.     equality?
  1253.  
  1254. A:    The best way is to use an accuracy threshold which is relative
  1255.     to the magnitude of the numbers being compared.
  1256.  
  1257. 14.6:    How do I round numbers?
  1258.  
  1259. A:    The simplest way is with code like (int)(x + 0.5) .
  1260.  
  1261. 14.7:    Where is C's exponentiation operator?
  1262.  
  1263. A:    Try using the pow() function.
  1264.  
  1265. 14.8:    The pre-#defined constant M_PI seems to be missing from
  1266.     <math.h>.
  1267.  
  1268. A:    That constant is not standard.
  1269.  
  1270. 14.9:    How do I test for IEEE NaN and other special values?
  1271.  
  1272. A:    There is not yet a portable way, but see the full list for
  1273.     ideas.
  1274.  
  1275. 14.11:    What's a good way to implement complex numbers in C?
  1276.  
  1277. A:    It is straightforward to define a simple structure and some
  1278.     arithmetic functions to manipulate them.
  1279.  
  1280. 14.12:    I'm looking for some mathematical library code.
  1281.  
  1282. A:    Ajay Shah maintains an index of free numerical software which is
  1283.     available where this FAQ list is archived (see question 20.40).
  1284.  
  1285. 14.13:    I'm having trouble with a Turbo C program which crashes and says
  1286.     something like "floating point formats not linked."
  1287.  
  1288. A:    Some compilers for small machines, including Borland's, attempt
  1289.     to leave out certain floating point support if it looks like it
  1290.     will not be needed.  The programmer must occasionally insert an
  1291.     extra, explicit call to a floating-point library routine to
  1292.     force loading of floating-point support.
  1293.  
  1294.  
  1295. Section 15. Variable-Length Argument Lists
  1296.  
  1297. 15.1:    I heard that you have to #include <stdio.h> before calling
  1298.     printf().  Why?
  1299.  
  1300. A:    So that a proper prototype for printf() will be in scope.
  1301.  
  1302. 15.2:    How can %f be used for both float and double arguments in
  1303.     printf()?
  1304.  
  1305. A:    In variable-length argument lists, types char and short int are
  1306.     promoted to int, and float is promoted to double.
  1307.  
  1308. 15.3:    Why don't function prototypes guard against mismatches in
  1309.     printf()'s arguments?
  1310.  
  1311. A:    Function prototypes do not provide any information about the
  1312.     number and types of variable arguments.
  1313.  
  1314. 15.4:    How can I write a function that takes a variable number of
  1315.     arguments?
  1316.  
  1317. A:    Use the <stdarg.h> header.
  1318.  
  1319. 15.5:    How can I write a function that takes a format string and a
  1320.     variable number of arguments, like printf(), and passes them to
  1321.     printf() to do most of the work?
  1322.  
  1323. A:    Use vprintf(), vfprintf(), or vsprintf().
  1324.  
  1325. 15.6:    How can I write a function analogous to scanf(), that calls
  1326.     scanf() to do most of the work?
  1327.  
  1328. A:    Unfortunately, vscanf and the like are not standard.
  1329.  
  1330. 15.7:    I have a pre-ANSI compiler, without <stdarg.h>.  What can I do?
  1331.  
  1332. A:    There's an older header, <varargs.h>, which offers about the
  1333.     same functionality.
  1334.  
  1335. 15.8:    How can I discover how many arguments a function was actually
  1336.     called with?
  1337.  
  1338. A:    Any function which takes a variable number of arguments must be
  1339.     able to determine *from the arguments themselves* how many of
  1340.     them there are.
  1341.  
  1342. 15.9:    My compiler isn't letting me declare a function that accepts
  1343.     *only* variable arguments.
  1344.  
  1345. A:    Standard C requires at least one fixed argument.
  1346.  
  1347. 15.10:    Why isn't "va_arg(argp, float)" working?
  1348.  
  1349. A:    Because the "default argument promotions" apply in variable-
  1350.     length argument lists, you should always use
  1351.     va_arg(argp, double).
  1352.  
  1353. 15.11:    I can't get va_arg() to pull in an argument of type pointer-to-
  1354.     function.
  1355.  
  1356. A:    Use a typedef.
  1357.  
  1358. 15.12:    How can I write a function which takes a variable number of
  1359.     arguments and passes them to some other function ?
  1360.  
  1361. A:    In general, you cannot.
  1362.  
  1363. 15.13:    How can I call a function with an argument list built up at run
  1364.     time?
  1365.  
  1366. A:    You can't.
  1367.  
  1368.  
  1369. Section 16. Strange Problems
  1370.  
  1371. 16.3:    This program crashes before it even runs!
  1372.  
  1373. A:    Look for very large, local arrays.
  1374.     (See also questions 11.12, 16.4, 16.5, and 18.4.)
  1375.  
  1376. 16.4:    I have a program that seems to run correctly, but then crashes
  1377.     as it's exiting.
  1378.  
  1379. A:    See the full list for ideas.
  1380.  
  1381. 16.5:    This program runs perfectly on one machine, but I get weird
  1382.     results on another.
  1383.  
  1384. A:    See the full list for a brief list of possibilities.
  1385.  
  1386. 16.6:    Why does the code "char *p = "hello, world!"; p[0] = 'H';"
  1387.     crash?
  1388.  
  1389. A:    String literals are not modifiable, except (in effect) when they
  1390.     are used as array initializers.
  1391.  
  1392. 16.8:    What does "Segmentation violation" mean?
  1393.  
  1394. A:    It generally means that your program tried to access memory it
  1395.     shouldn't have, invariably as a result of improper pointer use.
  1396.  
  1397.  
  1398. Section 17. Style
  1399.  
  1400. 17.1:    What's the best style for code layout in C?
  1401.  
  1402. A:    There is no one "best style," but see the full list for a few
  1403.     suggestions.
  1404.  
  1405. 17.3:    Is the code "if(!strcmp(s1, s2))" good style?
  1406.  
  1407. A:    Not particularly.
  1408.  
  1409. 17.4:    Why do some people write if(0 == x) instead of if(x == 0)?
  1410.  
  1411. A:    It's a trick to guard against the common error of writing
  1412.     if(x = 0) .
  1413.  
  1414. 17.5:    I came across some code that puts a (void) cast before each call
  1415.     to printf().  Why?
  1416.  
  1417. A:    To suppress warnings about otherwise discarded return values.
  1418.  
  1419. 17.8:    What is "Hungarian Notation"?  Is it worthwhile?
  1420.  
  1421. A:    It's a naming convention which encodes things about a variable's
  1422.     type in its name.
  1423.  
  1424. 17.9:    Where can I get the "Indian Hill Style Guide" and other coding
  1425.     standards?
  1426.  
  1427. A:    See the unabridged list.
  1428.  
  1429. 17.10:    Some people say that goto's are evil and that I should never use
  1430.     them.  Isn't that a bit extreme?
  1431.  
  1432. A:    Yes.  Absolute rules are an imperfect approach to good
  1433.     programming style.
  1434.  
  1435.  
  1436. Section 18. Tools and Resources
  1437.  
  1438. 18.1:    I'm looking for C development tools (cross-reference generators,
  1439.     code beautifiers, etc.).
  1440.  
  1441. A:    See the full list for a few names.
  1442.  
  1443. 18.2:    How can I track down these pesky malloc problems?
  1444.  
  1445. A:    See the full list for a list of tools.
  1446.  
  1447. 18.3:    What's a free or cheap C compiler I can use?
  1448.  
  1449. A:    See the full list for a brief catalog.
  1450.  
  1451. 18.4:    I just typed in this program, and it's acting strangely.  Can
  1452.     you see anything wrong with it?
  1453.  
  1454. A:    See if you can run lint first.
  1455.  
  1456. 18.5:    How can I shut off the "warning: possible pointer alignment
  1457.     problem" message which lint gives me for each call to malloc()?
  1458.  
  1459. A:    It may be easier simply to ignore the message, perhaps in an
  1460.     automated way with grep -v.
  1461.  
  1462. 18.7:    Where can I get an ANSI-compatible lint?
  1463.  
  1464. A:    See the unabridged list for two commercial products.
  1465.  
  1466. 18.8:    Don't ANSI function prototypes render lint obsolete?
  1467.  
  1468. A:    Not really.  A good compiler may match most of lint's
  1469.     diagnostics; few provide all.
  1470.  
  1471. 18.9:    Are there any C tutorials or other resources on the net?
  1472.  
  1473. A:    There are several of them.
  1474.  
  1475. 18.10:    What's a good book for learning C?
  1476.  
  1477. A:    There are far too many books on C to list here; the full list
  1478.     contains a few pointers.
  1479.  
  1480. 18.13:    Where can I find the sources of the standard C libraries?
  1481.  
  1482. A:    Several possibilites are listed in the full list.
  1483.  
  1484. 18.14:    I need code to parse and evaluate expressions.
  1485.  
  1486. A:    Several available packages are mentioned in the full list.
  1487.  
  1488. 18.15:    Where can I get a BNF or YACC grammar for C?
  1489.  
  1490. A:    See the ANSI Standard, or the unabridged list.
  1491.  
  1492. 18.15a:    Does anyone have a C compiler test suite I can use?
  1493.  
  1494. A:    See the full list for several sources.
  1495.  
  1496. 18.16:    Where and how can I get copies of all these freely distributable
  1497.     programs?
  1498.  
  1499. A:    See the regular postings in the comp.sources.unix and
  1500.     comp.sources.misc newsgroups, or the full version of this list,
  1501.     for information.
  1502.  
  1503.  
  1504. Section 19. System Dependencies
  1505.  
  1506. 19.1:    How can I read a single character from the keyboard without
  1507.     waiting for the RETURN key?
  1508.  
  1509. A:    Alas, there is no standard or portable way to do this sort of
  1510.     thing in C.
  1511.  
  1512. 19.2:    How can I find out how many characters are available for
  1513.     reading, or do a non-blocking read?
  1514.  
  1515. A:    These, too, are entirely operating-system-specific.
  1516.  
  1517. 19.3:    How can I display a percentage-done indication that updates
  1518.     itself in place, or show one of those "twirling baton" progress
  1519.     indicators?
  1520.  
  1521. A:    The character '\r' is a carriage return, and '\b' is a
  1522.     backspace.
  1523.  
  1524. 19.4:    How can I clear the screen, or print things in inverse video, or
  1525.     move the cursor?
  1526.  
  1527. A:    The only halfway-portable solution is the curses library.
  1528.  
  1529. 19.5:    How do I read the arrow keys?  What about function keys?
  1530.  
  1531. A:    Such things depend on the keyboard, operating system, and
  1532.     library you're using.
  1533.  
  1534. 19.6:    How do I read the mouse?
  1535.  
  1536. A:    What system are you using?
  1537.  
  1538. 19.7:    How can I do serial ("comm") port I/O?
  1539.  
  1540. A:    It's system-dependent.
  1541.  
  1542. 19.8:    How can I direct output to the printer?
  1543.  
  1544. A:    See the full list for ideas.
  1545.  
  1546. 19.9:    How do I send escape sequences to control a terminal or other
  1547.     device?
  1548.  
  1549. A:    By sending them.  ESC is '\033' in ASCII.
  1550.  
  1551. 19.10:    How can I do graphics?
  1552.  
  1553. A:    There is no portable way.
  1554.  
  1555. 19.11:    How can I check whether a file exists?
  1556.  
  1557. A:    You can try the access() or stat() functions.  Otherwise, the
  1558.     only guaranteed and portable way is to try opening the file.
  1559.  
  1560. 19.12:    How can I find out the size of a file, prior to reading it in?
  1561.  
  1562. A:    You might be able to get an estimate using stat() or
  1563.     fseek/ftell.
  1564.  
  1565. 19.13:    How can a file be shortened in-place without completely clearing
  1566.     or rewriting it?
  1567.  
  1568. A:    There are various ways to do this, but there is no portable
  1569.     solution.
  1570.  
  1571. 19.14:    How can I insert or delete a line in the middle of a file?
  1572.  
  1573. A:    Short of rewriting the file, you probably can't.
  1574.  
  1575. 19.15:    How can I recover the file name given an open file descriptor?
  1576.  
  1577. A:    This problem is, in general, insoluble.  It is best to remember
  1578.     the names of files yourself when you open them
  1579.  
  1580. 19.16:    How can I delete a file?
  1581.  
  1582. A:    The Standard C Library function is remove().
  1583.  
  1584. 19.17:    What's wrong with the call fopen("c:\newdir\file.dat", "r")?
  1585.  
  1586. A:    You probably need to double those backslashes.
  1587.  
  1588. 19.18:    How can I increase the allowable number of simultaneously open
  1589.     files?
  1590.  
  1591. A:    Check your system documentation.
  1592.  
  1593. 19.20:    How can I read a directory in a C program?
  1594.  
  1595. A:    See if you can use the opendir() and readdir() routines.
  1596.  
  1597. 19.22:    How can I find out how much memory is available?
  1598.  
  1599. A:    Your operating system may provide a routine which returns this
  1600.     information.
  1601.  
  1602. 19.23:    How can I allocate arrays or structures bigger than 64K?
  1603.  
  1604. A:    Some operating systems won't let you.
  1605.  
  1606. 19.24:    What does the error message "DGROUP exceeds 64K" mean?
  1607.  
  1608. A:    It means that you have too much static data.
  1609.  
  1610. 19.25:    How can I access memory located at a certain address?
  1611.  
  1612. A:    Set a pointer to the absolute address.
  1613.  
  1614. 19.27:    How can I invoke another program from within a C program?
  1615.  
  1616. A:    Use system().
  1617.  
  1618. 19.30:    How can I invoke another program and trap its output?
  1619.  
  1620. A:    Unix and some other systems provide a popen() routine.
  1621.  
  1622. 19.31:    How can my program discover the complete pathname to the
  1623.     executable from which it was invoked?
  1624.  
  1625. A:    argv[0] may contain all or part of the pathname.  You may be
  1626.     able to duplicate the command language interpreter's search path
  1627.     logic to locate the executable.
  1628.  
  1629. 19.32:    How can I automatically locate a program's configuration files
  1630.     in the same directory as the executable?
  1631.  
  1632. A:    It's hard; see also question 19.31 above.
  1633.  
  1634. 19.33:    How can a process change an environment variable in its caller?
  1635.  
  1636. A:    If it's possible to do so at all, it's system dependent.
  1637.  
  1638. 19.36:    How can I read in an object file and jump to routines in it?
  1639.  
  1640. A:    You want a dynamic linker or loader.
  1641.  
  1642. 19.37:    How can I implement a delay, or time a user's response, with sub-
  1643.     second resolution?
  1644.  
  1645. A:    Unfortunately, there is no portable way.
  1646.  
  1647. 19.38:    How can I trap or ignore keyboard interrupts like control-C?
  1648.  
  1649. A:    Use signal().
  1650.  
  1651. 19.39:    How can I handle floating-point exceptions gracefully?
  1652.  
  1653. A:    Take a look at matherr() and signal(SIGFPE).
  1654.  
  1655. 19.40:    How do I...  Use sockets?  Do networking?  Write client/server
  1656.     applications?
  1657.  
  1658. A:    These questions have more to do with the networking facilities
  1659.     you have available than they do with C.
  1660.  
  1661. 19.40b:    How do I use BIOS calls?  How can I write ISR's?  How can I
  1662.     create TSR's?
  1663.  
  1664. A:    These are very particular to specific systems.
  1665.  
  1666. 19.41:    But I can't use all these nonstandard, system-dependent
  1667.     functions, because my program has to be ANSI compatible!
  1668.  
  1669. A:    That's an impossible requirement.  Any real program requires at
  1670.     least a few services which ANSI doesn't define.
  1671.  
  1672.  
  1673. Section 20. Miscellaneous
  1674.  
  1675. 20.1:    How can I return multiple values from a function?
  1676.  
  1677. A:    Either pass pointers to several locations which the function can
  1678.     fill in, or have the function return a structure containing the
  1679.     desired values.
  1680.  
  1681. 20.3:    How do I access command-line arguments?
  1682.  
  1683. A:    Via main()'s argv parameter.
  1684.  
  1685. 20.5:    How can I write data files which can be read on other machines
  1686.     with different data formats?
  1687.  
  1688. A:    The most portable solution is to use text files.
  1689.  
  1690. 20.6:    How can I call a function, given its name as a string?
  1691.  
  1692. A:    The most straightforward thing to do is to maintain a
  1693.     correspondence table of names and function pointers.
  1694.  
  1695. 20.8:    How can I implement sets or arrays of bits?
  1696.  
  1697. A:    Use arrays of char or int, with a few macros to access the
  1698.     desired bit at the proper index.
  1699.  
  1700. 20.9:    How can I determine whether a machine's byte order is big-endian
  1701.     or little-endian?
  1702.  
  1703. A:    Use barely-portable pointer or union tricks.
  1704.  
  1705. 20.10:    How can I convert integers to binary or hexadecimal?
  1706.  
  1707. A:    Internally, integers are already in binary.  During I/O, you may
  1708.     be able to select a base.
  1709.  
  1710. 20.11:    Can I use base-2 constants (something like 0b101010)?
  1711.     Is there a printf() format for binary?
  1712.  
  1713. A:    No, on both counts.
  1714.  
  1715. 20.12:    What is the most efficient way to count the number of bits which
  1716.     are set in a value?
  1717.  
  1718. A:    Many "bit-fiddling" problems like this one can be sped up and
  1719.     streamlined using lookup tables.
  1720.  
  1721. 20.13:    How can I make my code more efficient?
  1722.  
  1723. A:    Efficiency is not important nearly as often as people tend to
  1724.     think it is.  Most of the time, by simply paying attention to
  1725.     good algorithm choices, perfectly acceptable results can be
  1726.     achieved.
  1727.  
  1728. 20.14:    Are pointers really faster than arrays?  How much do function
  1729.     calls slow things down?
  1730.  
  1731. A:    Precise answers to these and many similar questions depend on
  1732.     the processor and compiler in use.
  1733.  
  1734. 20.17:    Is there a way to switch on strings?
  1735.  
  1736. A:    Not directly.
  1737.  
  1738. 20.18:    Is there a way to have non-constant case labels (i.e. ranges or
  1739.     arbitrary expressions)?
  1740.  
  1741. A:    No.
  1742.  
  1743. 20.19:    Are the outer parentheses in return statements really optional?
  1744.  
  1745. A:    Yes.
  1746.  
  1747. 20.20:    Why don't C comments nest?  Are they legal inside quoted
  1748.     strings?
  1749.  
  1750. A:    C comments don't nest because PL/I's comments don't either.  The
  1751.     character sequences /* and */ are not special within double-
  1752.     quoted strings.
  1753.  
  1754. 20.24:    Why doesn't C have nested functions?
  1755.  
  1756. A:    They were deliberately left out of C as a simplification.
  1757.  
  1758. 20.25:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  1759.     from C?
  1760.  
  1761. A:    The answer is entirely dependent on the machine and the specific
  1762.     calling sequences of the various compilers in use.
  1763.  
  1764. 20.26:    Does anyone know of a program for converting Pascal or FORTRAN
  1765.     to C?
  1766.  
  1767. A:    Several freely distributable programs are available, namely
  1768.     ptoc, p2c, and f2c.  See the full list for details.
  1769.  
  1770. 20.27:    Can I use a C++ compiler to compile C code?
  1771.  
  1772. A:    Not necessarily; C++ is not a strict superset of C.
  1773.  
  1774. 20.28:    I need to compare two strings for close, but not necessarily
  1775.     exact, equality.
  1776.  
  1777. A:    One approach for doing this sort of thing involves the "soundex"
  1778.     algorithm.
  1779.  
  1780. 20.29:    What is hashing?
  1781.  
  1782. A:    A mapping of strings (or other data structures) to integers, for
  1783.     easier searching.
  1784.  
  1785. 20.31:    How can I find the day of the week given the date?
  1786.  
  1787. A:    Use mktime() Zeller's congruence, or some code in the full list.
  1788.  
  1789. 20.32:    Will 2000 be a leap year?
  1790.  
  1791. A:    Yes.
  1792.  
  1793. 20.34:    How do you write a program which produces its own source code as
  1794.     its output?
  1795.  
  1796. A:    Here's one:
  1797.  
  1798.         char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
  1799.         main(){printf(s,34,s,34);}
  1800.  
  1801. 20.35:    What is "Duff's Device"?
  1802.  
  1803. A:    It's a devastatingly deviously unrolled byte-copying loop.  See
  1804.     the full list for details.
  1805.  
  1806. 20.36:    When will the next Obfuscated C Code Contest be held?  How can I
  1807.     get a copy of previous winning entries?
  1808.  
  1809. A:    See the full list, or send e-mail to judges@toad.com .
  1810.  
  1811. 20.37:    What was the entry keyword mentioned in K&R1?
  1812.  
  1813. A:    It was reserved to allow functions with multiple, differently-
  1814.     named entry points, but it has been withdrawn.
  1815.  
  1816. 20.38:    Where does the name "C" come from, anyway?
  1817.  
  1818. A:    C was derived from B, which was inspired by BCPL, which was a
  1819.     simplification of CPL.
  1820.  
  1821. 20.39:    How do you pronounce "char"?
  1822.  
  1823. A:    Like the English words "char," "care," or "car" (your choice).
  1824.  
  1825. 20.40:    Where can I get extra copies of this list?
  1826.  
  1827. A:    An up-to-date copy may be obtained from ftp.eskimo.com in
  1828.     directory u/s/scs/C-faq/.  You can also just pull it off the
  1829.     net; the unabridged version is normally posted on the first of
  1830.     each month, with an Expires: line which should keep it around
  1831.     all month.  It is also posted to the newsgroups comp.answers and
  1832.     news.answers .  Several sites archive news.answers postings and
  1833.     other FAQ lists, including this one; two sites are rtfm.mit.edu
  1834.     (directory pub/usenet), and ftp.uu.net (directory usenet).  An
  1835.     archie server should help you find others.
  1836.  
  1837.     A hypertext version of this FAQ list is available at
  1838.     http://www.eskimo.com/~scs/C-faq.top.html .
  1839.     An extended version is being published by Addison-Wesley
  1840.     as _C Programming FAQs: Frequently Asked Questions_
  1841.     (ISBN 0-201-84519-9).
  1842.  
  1843.                     Steve Summit
  1844.                     scs@eskimo.com
  1845.  
  1846. This article is Copyright 1988, 1990-1995 by Steve Summit.
  1847. Content from the book _C Programming FAQs: Frequently Asked Questions_
  1848. is made available here by permission of the author and the publisher as
  1849. a service to the community.  It is intended to complement the use of the
  1850. published text and is protected by international copyright laws.  The
  1851. content is made available here and may be accessed freely for personal
  1852. use but may not be published or retransmitted without written
  1853. permission.
  1854.